<template>
  <div class="go-out">
    <tabs :eventBus="true" @closeTabs="closeTabs" />
    <filtrate
      @selectConfirm="selectConfirm"
      ref="Filtrate"
      :echoSelect="InitselectOkList"
      :data="searchList"
    />
    <div class="flex-1 overflow-auto px-10px" ref="workbenchOutList">
      <PullRefresh v-model="refreshing" @refresh="onRefresh">
        <List
          v-model="loading"
          :finished="finished"
          :finished-text="todoListData.length ? '没有更多了' : ''"
          @load="onLoad"
          :immediate-check="false"
        >
          <template v-if="!todoListData.length && !loading">
            <div
              class="h-full flex-1 flex flex-col justify-center"
              ref="emptyData"
            >
              <Empty :image="emptyIcon" image-size="34">
                <div slot="description" class="text-dark-300 select-none">
                  暂无数据
                </div>
              </Empty>
            </div>
          </template>
          <template v-else>
            <list-data
              :data="todoListData"
              @view="(item) => handleView(item)"
              @cancel="(item) => handleCancel(item)"
              @confirm="(item) => handleConfirm(item)"
              @apply="(item) => handleApply(item)"
              @clock-in="(item) => handleClockIn(item)"
              @clock-out="(item) => handleClockOut(item)"
              @follow="(item) => handleFollow(item)"
            />
          </template>
        </List>
      </PullRefresh>
    </div>
  </div>
</template>

<script>
import _ from "lodash";
import tabs from "./components/tabs.vue";
import listData from "./components/list.vue";
import filtrate from "./components/filter.vue";
import emptyIcon from "@/assets/icon/empty.png";
import { PullRefresh, List, Toast, Empty } from "vant";
import { getTodoOutList, getTodoOutMenu } from "@/services/visit";
export default {
  components: {
    tabs,
    listData,
    filtrate,
    PullRefresh,
    List,
    Empty,
  },
  data() {
    return {
      emptyIcon,
      refreshing: false,
      loading: false,
      finished: false,
      todoListData: [],
      page: {
        pageNum: 1,
      },
      searchList: {}, //筛选条件
      InitselectOkList: {}, //原始筛选数据
      selectOkList: {}, //筛选后的数据
      visitListScrollTop: 0, //滚动位置
    };
  },
  created() {
    this.getTodoOutMenuSearch();
    this.initData();
  },
  activated() {
    if (this.$store.state.work.loadDataWorkGoTo) {
      this.refreshDataLoad();
      this.initData();
    }
    //滚动
    if (
      this.$refs.workbenchOutList &&
      !this.$store.state.work.loadDataWorkGoTo
    ) {
      this.$refs.workbenchOutList.scrollTop = this.visitListScrollTop;
    }
  },
  deactivated() {
    if (this.$route.path == "/business") {
      console.log("销毁");
      //销毁滚动
      this.$refs.workbenchOutList.removeEventListener(
        "scroll",
        this.scrollWorkbench
      );
    }
  },
  mounted() {
    //监听滚动
    if (this.$refs.workbenchOutList) {
      this.$refs.workbenchOutList.addEventListener(
        "scroll",
        this.scrollWorkbench
      );
    }
  },
  methods: {
    getTodoOutMenuSearch() {
      //搜索条件
      getTodoOutMenu().then((res) => {
        if (res) {
          for (let key in res) {
            res[key].map((item) => {
              item.key = key + item.type;
              return item;
            });
          }
          this.searchList = res;
        }
      });
    },
    selectConfirm(data) {
      // 保存原始筛选数据
      this.InitselectOkList = data;
      var parmas = this.getSelectedData(data);
      this.selectOkList = parmas; // 保存API处理数据
      this.onData(parmas);
    },
    getSelectedData(data) {
      //筛选回调
      let todoType, stateList, followStateList, time;
      if (data.followTypeList && data.followTypeList[0]) {
        //待办事项类型
        todoType = data.followTypeList[0].type;
      }
      if (data.goOutTime && data.goOutTime[0]) {
        //时间分割
        time = data.goOutTime[0].name.split(" ");
      }
      stateList = this.selectConfirmDispose("statusList", data); //状态
      followStateList = this.selectConfirmDispose("outTypeList", data); //跟进状态
      let params = {
        //参数汇总
        pageNum: this.page.pageNum,
        stateList,
        todoType,
        followStateList,
        startTime: time ? time[0] : null,
        endTime: time ? time[2] : null,
      };
      return params;
    },
    selectConfirmDispose(key, data) {
      let arrayType = new Array();
      if (data[key].length > 0) {
        data[key].map((item) => {
          arrayType.push(item.type);
        });
      }
      return arrayType;
    },
    onRefresh() {
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.refreshing = true;
      this.page.pageNum = 1;
      this.finished = false;
      this.loading = true;
      this.onData();
    },
    initData() {
      // 重新加载数据
      this.loading = true;
      this.onData();
    },
    onData: _.throttle(function (data) {
      let params = {
        ...this.page,
        ...this.selectOkList,
      };
      getTodoOutList(params)
        .then((res) => {
          if (this.refreshing) {
            this.todoListData = [];
            this.refreshing = false;
          }
          if (data == "onLoad") {
            this.todoListData = this.todoListData.concat(res.data);
          } else {
            this.todoListData = res.data;
          }
          // 加载状态结束
          this.loading = false;
          // 数据全部加载完成
          if (this.todoListData.length >= res.total) {
            this.finished = true;
          } else {
            this.finished = false;
          }
          this.noDataHeight();
        })
        .catch((err) => {
          console.log(err);
          this.refreshing = false;
          this.loading = false;
          this.finished = true; //加载完成
          Toast.fail(err);
          this.noDataHeight();
        });
    }, 300),
    /**
     * 上拉触底
     */
    onLoad: _.throttle(function () {
      this.loading = true;
      ++this.page.pageNum;
      this.onData("onLoad");
    }, 300),

    closeTabs(row) {
      let res = this.InitselectOkList;
      for (let key in res) {
        res[key].map((item, index) => {
          if (item.key === row.key) {
            res[key].splice(index, 1);
          }
        });
      }
      this.page.pageNum = 1;
      this.selectConfirm(res); //执行数据过滤
    },
    /**
     * 设置没有内容的高度
     */
    noDataHeight() {
      this.$nextTick(() => {
        if (this.$refs.workbenchOutList) {
          let height = this.$refs.workbenchOutList.clientHeight;
          let tempDom = this.$refs.emptyData;
          if (!this.todoListData.length && !this.loading) {
            tempDom.style.height = height - 10 + "px";
          } else {
            if (tempDom) {
              tempDom.style.height = null;
            }
          }
        }
      });
    },
    /**
     * 重新刷新数据
     */
    refreshDataLoad() {
      this.page.pageNum = 1;
      this.todoListData = [];
    },
    /**
     * 重置加载数据
     */
    loadDataWork() {
      this.$store.commit(`work/set_loadDataWorkGoTo`, {
        value: false,
      });
    },
    /**
     * 外出申请
     */
    handleApply({ todoType, id }) {
      this.loadDataWork(); //重置加载数据
      this.$router.push({
        path: "/workbench/apply",
        query: {
          id,
          type: todoType,
          load: "set_loadDataWorkGoTo",
        },
      });
    },
    /**
     * 签到
     */
    handleClockIn({ todoType, id }) {
      this.loadDataWork(); //重置加载数据
      this.$router.push({
        path: "/workbench/clock-in",
        query: {
          id,
          type: todoType,
          load: "set_loadDataWorkGoTo",
        },
      });
    },
    /**
     * 签出
     */
    handleClockOut({ todoType, id }) {
      this.loadDataWork(); //重置加载数据
      this.$router.push({
        path: "/workbench/clock-out",
        query: {
          id,
          type: todoType,
          load: "set_loadDataWorkGoTo",
        },
      });
    },
    /**
     * 跟进
     */
    handleFollow({ todoType, id }) {
      this.loadDataWork(); //重置加载数据
      this.$router.push({
        path: "/workbench/follow",
        query: {
          id,
          type: todoType,
          load: "set_loadDataWorkGoTo",
        },
      });
    },
    /**
     * 查看详情
     */
    handleView({ id, todoType, status }) {
      this.loadDataWork(); //重置加载数据
      this.$router.push({
        path: "/workbench/view",
        query: {
          id,
          type: todoType,
          status,
        },
      });
    },
    // 外出取消
    handleCancel({ todoType, id }) {
      this.loadDataWork(); //重置加载数据
      this.$router.push({
        path: "/workbench/cancel",
        query: {
          id,
          type: todoType,
          load: "set_loadDataWorkGoTo",
        },
      });
    },
    scrollWorkbench() {
      // 声明dom
      var workbenchListDom = this.$refs.workbenchOutList;
      //顶部距离
      var scrollTop = workbenchListDom.scrollTop;
      //记录滚动的高度
      this.visitListScrollTop = scrollTop;
    },
  },
};
</script>

<style lang="scss" scoped>
.go-out {
  display: flex;
  flex-direction: column;
  ::v-deep {
    .van-popup--bottom.van-popup--round {
      background: #ffffff;
      box-shadow: 0px -2px 8px 0px rgba(0, 0, 0, 0.09);
      border-radius: 10px 10px 0px 0px;
    }
  }
}
</style>
